package com.xfatm.killer.entity;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.widget.Toast;

import com.xfatm.killer.util.Activitys;
import com.xfatm.killer.util.CommandExecution;
import com.xfatm.killer.util.SharedPreferencesUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Created by wenjie on 2018/3/25.
 */

public class AppInfoController {

    private static AppInfoController appInfoController;
    private List<AppInfo> allApps=new ArrayList<>();
    private List<AppInfo> normalApps=new ArrayList<>();
    private List<AppInfo> sysApps=new ArrayList<>();
    private List<AppInfo> selectApps=new ArrayList<>();
    private Set<String> selectAppSet;
    private SelectAppInfoAdapter selectAppInfoAdapter;

    private AppInfoController(){
        init();
    }
    public static AppInfoController getInstance(){
        if(appInfoController==null){
            synchronized (AppInfoController.class){
                if(appInfoController==null){
                    appInfoController=new AppInfoController();
                }
            }
        }
        return appInfoController;
    }

    public static boolean isInit(){
        return appInfoController!=null;
    }

    private void init(){
        //获取所有app并分类
        selectAppSet = SharedPreferencesUtils.readSet(Activitys.top(),"selectedApp");
        for(AppInfo appInfo:(allApps=getAppInfos())){
            //排除不能打开的app
            if(!selectAppSet.contains(appInfo.getPackageName())&&!appInfo.isHasActivity()){
                continue;
            }

            if(appInfo.isSystem()){
                sysApps.add(appInfo);
            }else{
                normalApps.add(appInfo);
            }
            if(selectAppSet.contains(appInfo.getPackageName())){
                selectApps.add(appInfo);
                appInfo.setChecked(true);
            }
            //判断应用是否被打开过
           appInfo.setEnable(SharedPreferencesUtils.readBooleanForEnable(Activitys.top(),appInfo.getPackageName()));
        }
    }

    public void addSelectApp(AppInfo appInfo){
        selectApps.add(appInfo);
        selectAppSet.add(appInfo.getPackageName());
        setSelectAppSet(selectAppSet);
    }

    public void removeSelectApp(AppInfo appInfo){
        Iterator<AppInfo> aps=selectApps.iterator();
        while(aps.hasNext()){
            if(aps.next().getPackageName().equals(appInfo.getPackageName())){
                aps.remove();
                break;
            }
        }
        selectAppSet.remove(appInfo.getPackageName());
        setSelectAppSet(selectAppSet);
    }

    public Set<String> getSelectAppSet() {
        return selectAppSet;
    }

    public SelectAppInfoAdapter getSelectAppInfoAdapter() {
        return selectAppInfoAdapter;
    }

    public void setSelectAppInfoAdapter(SelectAppInfoAdapter selectAppInfoAdapter) {
        this.selectAppInfoAdapter = selectAppInfoAdapter;
    }

    private void setSelectAppSet(Set<String> selectAppSet) {
        SharedPreferencesUtils.saveSet(Activitys.top(),"selectedApp",selectAppSet);
        this.selectAppSet = selectAppSet;
    }

    public List<AppInfo> getAllApps() {
        Collections.sort(allApps);
        return allApps;
    }

    public List<AppInfo> getNormalApps() {
        Collections.sort(normalApps);
        return normalApps;
    }

    public List<AppInfo> getSysApps() {
        Collections.sort(sysApps);
        return sysApps;
    }

    public List<AppInfo> getSelectApps() {
        Collections.sort(selectApps);
        return selectApps;
    }

    public int disableAppInThread(AppInfo appInfo){
        appInfo.setEnable(false);
        CommandExecution.CommandResult result=CommandExecution.execCommand("pm disable "+appInfo.getPackageName(),true);
        SharedPreferencesUtils.saveBooleanForEnable(Activitys.top(),appInfo.getPackageName(),false);
        return result.result;
    }

    public void disableAllInThread(){
        for(AppInfo appInfo:selectApps){
            if(appInfo.isEnable()){
                disableAppInThread(appInfo);
            }
        }
    }

    public int disableApp(AppInfo appInfo){
        appInfo.setEnable(false);
        CommandExecution.CommandResult result=CommandExecution.execCommand("pm disable "+appInfo.getPackageName(),true);
        SharedPreferencesUtils.saveBooleanForEnable(Activitys.top(),appInfo.getPackageName(),false);
        getSelectAppInfoAdapter().notifyDataSetChanged();
        return result.result;
    }

    public void disableAll(){
        for(AppInfo appInfo:selectApps){
            if(appInfo.isEnable()){
                disableApp(appInfo);
            }
        }
    }

    public void enableApp(AppInfo appInfo){
        appInfo.setEnable(true);
        CommandExecution.execCommand("pm enable "+appInfo.getPackageName(),true);
        SharedPreferencesUtils.saveBooleanForEnable(Activitys.top(),appInfo.getPackageName(),true);
        getSelectAppInfoAdapter().notifyDataSetChanged();
    }

    public void enableAppInThread(AppInfo appInfo){
        appInfo.setEnable(true);
        CommandExecution.execCommand("pm enable "+appInfo.getPackageName(),true);
        SharedPreferencesUtils.saveBooleanForEnable(Activitys.top(),appInfo.getPackageName(),true);
    }

    public void enableAllAppInThread(){
        for(AppInfo appInfo:selectApps){
            if(!appInfo.isEnable()){
                enableAppInThread(appInfo);
            }
        }
    }

    private List<AppInfo> getAppInfos(){
        PackageManager manager= Activitys.top().getPackageManager();
        List<AppInfo> data=new ArrayList<>();
        List<PackageInfo> packageInfos= manager.getInstalledPackages(0);
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);

        // 通过getPackageManager()的queryIntentActivities方法遍历,得到所有能打开的app的packageName
        List<ResolveInfo>  resolveinfoList =manager.queryIntentActivities(resolveIntent, 0);
        Set<String> allowPackages=new HashSet<>();
        for (ResolveInfo resolveInfo:resolveinfoList){
            allowPackages.add(resolveInfo.activityInfo.packageName);
        }

        for(PackageInfo info:packageInfos){
            //排除不能打开的应用合系统应用
            if(info.packageName.equals("com.xfatm.killer")){
                continue;
            }
            AppInfo appInfo=new AppInfo();
            appInfo.setAppName(info.applicationInfo.loadLabel(manager).toString());
            appInfo.setPackageName(info.packageName);
            appInfo.setIcon(info.applicationInfo.loadIcon(manager));
            data.add(appInfo);
            if (((info.applicationInfo.flags& ApplicationInfo.FLAG_SYSTEM) == 0)) {
                //非系统app
               appInfo.setSystem(false);
            }else{
               appInfo.setSystem(true);
            }
            appInfo.setHasActivity(allowPackages.contains(info.packageName));
        }
        Collections.sort(data);
        return data;
    }
}
